// EtyMain.cpp

#include <iostream>
#include <Windows.h>
#include <google/protobuf/util/json_util.h>
#include "PkgUser.pb.h"

int main() {
	SetConsoleOutputCP(65001); // 此文件是utf8格式的，所以，要设置为utf8显示
	std::cout << "code page " << GetConsoleCP() << ", " << GetConsoleOutputCP() << "\n";
	std::cout << "A test for converting proto to json.\n";
#if 1
#endif
	PkgUser::PhtList_Respond* oRpd = new PkgUser::PhtList_Respond();
	oRpd->set_code(0x3001);
	oRpd->set_command("Usr_Pht_List");
	oRpd->set_result("0");
	oRpd->set_message("成功");

	PkgUser::PhtList_Item* oItm = NULL;
	oItm = oRpd->add_list();
	oItm->set_pht_idntifr("1");
	oItm->set_pht_status("1");
	oItm->set_url_finalztion("https://www.baidu.com/1.jpg");
	// proto to json
	std::string sTxt = "";
	google::protobuf::util::JsonPrintOptions tOpt;
	tOpt.preserve_proto_field_names = true;
	google::protobuf::util::MessageToJsonString(*oRpd, &sTxt, tOpt);
	std::cout << "PhtList_Respond is: " << sTxt << "\n";

	unsigned char aBfr[1024] = { 0 };
	int nBlk = 1024;
#if 0
	FILE* hFle = fopen("d:\\1.dat", "r+b");
	nBlk = fread(aBfr, 1, nBlk, hFle);
	fclose(hFle);
#else
	google::protobuf::io::ArrayOutputStream tBfr(aBfr, nBlk);
	google::protobuf::io::CodedOutputStream tOut(&tBfr);
	nBlk = oRpd->ByteSizeLong();
	oRpd->SerializeToCodedStream(&tOut);
	nBlk = tOut.ByteCount();
#endif
	oRpd->clear_list();
	delete oRpd;
	oRpd = NULL;
	//delete oItm; // deleted already
	oItm = NULL;

	PkgUser::MsgCommon_Respond tPkg;
	tPkg.ParseFromArray(aBfr, 5);

	switch (tPkg.code()) {
		case 0x3001: {
			oRpd = new PkgUser::PhtList_Respond();
			oRpd->ParseFromArray(aBfr, nBlk);

			sTxt = "";
			google::protobuf::util::MessageToJsonString(*oRpd, &sTxt, tOpt);
			std::cout << "PhtList_Respond is: " << sTxt << "\n";

			sTxt = "";
			delete oRpd;
			oRpd = NULL;
		}
		break;
		default:
		break;
	}
	// json to proto
	sTxt = "{\"result\":\"0\",\"code\":12289,\"message\":\"成功\",\"list\":[{\"pht_status\":\"1\",\"url_finalztion\":\"https://www.baidu.com/1.jpg\",\"pht_idntifr\":\"1\"}],\"command\":\"Usr_Pht_List\"}";
	oRpd = new PkgUser::PhtList_Respond();
	google::protobuf::util::JsonStringToMessage(sTxt, oRpd);
	sTxt = "";
	google::protobuf::util::MessageToJsonString(*oRpd, &sTxt, tOpt);
	std::cout << "PhtList_Respond is: " << sTxt << "\n";
}
